package com.ershui.blog.boke.service.impl;

import com.ershui.blog.article.domain.LCategory;
import com.ershui.blog.boke.domain.*;
import com.ershui.blog.boke.mapper.BlogMapper;
import com.ershui.blog.boke.mapper.LLeaveWordsMapper;
import com.ershui.blog.boke.service.BlogService;
import com.ershui.blog.system.domain.AjaxResult;
import com.ershui.blog.system.util.IpUtil;
import com.ershui.blog.system.util.MailUti;
import com.ershui.blog.system.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Value("${spring.mail.username}")
    private String from;
    @Value("${ershui.adminEmail}")
    private String to;
    @Value("${ershui.blogUrl}")
    private String bokeUrl;

    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private LLeaveWordsMapper leaveWordsMapper;
    @Autowired
    private MailUti mailUtil;

    SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    //文章总数
    @Override
    public Integer selectArticleCount(BlogArticleInDto inDto) {
        Map<String,Object> param=new HashMap<>();
        param.put("categoryId",inDto.getCategoryId());
        param.put("keyword",inDto.getKeyword());
        Integer count=blogMapper.selectArticleCount(param);
        return count;
    }

    //文章一览
    @Override
    public List<BlogArticleOutDto> selectArticlesByParam(BlogArticleInDto inDto) {
        Map<String,Object> param=new HashMap<>();
        param.put("categoryId",inDto.getCategoryId());
        param.put("keyword",inDto.getKeyword());
        List<BlogArticleOutDto> articleList=blogMapper.selectArticlesByParam(param);
        for(BlogArticleOutDto  article:articleList){
            Calendar ca = Calendar.getInstance();
            ca.setTime(article.getCreateTime());
            Integer dayInt=ca.get(Calendar.DAY_OF_MONTH);
            article.setDay(dayInt.toString());
            Integer monthInt=ca.get(Calendar.MONTH)+1;
            article.setMonth(monthInt.toString());
            Integer yearInt=ca.get(Calendar.YEAR);
            article.setYear(yearInt.toString());
            if(article.getContent().length()>300){
                article.setContentShort(article.getContent().substring(0,300));
            }else{
                article.setContentShort(article.getContent());
            }
            if(article.getViewNum()==null){
                article.setViewNum(0);
            }
        }
        return articleList;
    }


    //分类一览
    @Override
    public List<LCategory> selectCategorys() {
        return blogMapper.selectCategorys();
    }

    @Override
    public BlogArticleOutDto viewArticle(Long id) {
        //查询文章详细信息
        BlogArticleOutDto article=blogMapper.selectArticleById(id);
        Calendar ca = Calendar.getInstance();
        ca.setTime(article.getCreateTime());
        Integer dayInt=ca.get(Calendar.DAY_OF_MONTH);
        article.setDay(dayInt.toString());
        Integer monthInt=ca.get(Calendar.MONTH)+1;
        article.setMonth(monthInt.toString());
        Integer yearInt=ca.get(Calendar.YEAR);
        article.setYear(yearInt.toString());
        if(article.getContent().length()>300){
            article.setContentShort(article.getContent().substring(0,300));
        }else{
            article.setContentShort(article.getContent());
        }
        if(article.getViewNum()==null){
            article.setViewNum(0);
        }
        article.setCreateTimeStr(sdf.format(article.getCreateTime()));
        //浏览数增加1
        blogMapper.addArticleViewNum(id);
        return article;
    }

    //添加留言
    @Override
    public int insertLeaveWords(LLeaveWords leaveWords, HttpServletRequest request) {
        //根据IP获取物理地址待完善
        String ipAddr=IpUtil.getIpAddr(request);
        String address=IpUtil.GetAddressByIP(ipAddr);
        leaveWords.setMemberAddress(address);
        leaveWords.setMemberIp(ipAddr);
        leaveWords.setCreateTime(new Date());

        //如果是选中留言回复的，对应邮件应该发送给留言者对应的邮箱，否则发给系统管理员邮箱
        Boolean noticeFlag=true;
        if(leaveWords.getParentId()!=null){
            LLeaveWords parentLeaveWord=leaveWordsMapper.selectById(leaveWords.getParentId());
            to=parentLeaveWord.getMemberEmail();
            //若选择不通知，则不发送邮件通知
            if(parentLeaveWord.getIsNotice()==0){
                noticeFlag=false;
            }
        }
        //邮件通知，有人留言了
        String  text="<h4>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+leaveWords.getMemberName()+"【"+leaveWords.getMemberEmail()+"】于"+sdf.format(leaveWords.getCreateTime())+" 在系统中留言，留言内容：</h4></br>"+
                    "<h3>"+leaveWords.getContent()+"</h3></br>"+
                    "<a href='"+bokeUrl+"'>博客地址链接</a>";
        if(noticeFlag) {
            mailUtil.sendHtmlMail("二水博客留言板通知", text, to, from);
        }
        return leaveWordsMapper.insert(leaveWords);

    }

    //留言一览
    @Override
    public List<LeaveWordsOutDto> GetLeaveWords(LeaveWordsInDto inDto) {
        List<LeaveWordsOutDto> leaveOutList=new ArrayList<>();

        Map<String,Object> param= MapUtil.toMap(inDto);
        List<LeaveWordsOutDto> list=leaveWordsMapper.getParentLeaveWords(param);
        //获取所有一级评论
        for(LeaveWordsOutDto leaveWord:list){
            leaveWord.setCreatetime(sdf.format(leaveWord.getCreateDate()));
            if(leaveWord.getParentId()==null){
                leaveOutList.add(leaveWord);
            }
        }
        //获取所有子评论
        for(LeaveWordsOutDto leaveWord:leaveOutList){
            getChildIds(leaveWord,list);
        }
        return leaveOutList;
    }

    /**
     * 热门文章，按照浏览量倒叙排列
     * @return
     */
    @Override
    public List<BlogArticleOutDto> selectHotArticle() {
        List<BlogArticleOutDto> list=blogMapper.selectHotArticle();
        return list;
    }

    @Override
    public List<SelectDiaryOutDto> selectDiayList() {
        SimpleDateFormat sdf=new SimpleDateFormat("MM月dd日");
        List<SelectDiaryOutDto> data=new ArrayList<>();

        List<Integer>  years=blogMapper.selectYear();
        List<SelectDiaryDto> list=blogMapper.selectDiaryList();
        for(Integer  year:years){
            SelectDiaryOutDto outDto=new SelectDiaryOutDto();
            List<SelectDiaryDto> temp=new ArrayList<>();
            for(SelectDiaryDto dto:list){
                if(year.intValue()==dto.getYear().intValue()){
                    dto.setMonthDay(sdf.format(dto.getCreateDate()));
                    outDto.setYear(year);
                    temp.add(dto);
                }
            }
            outDto.setData(temp);
            data.add(outDto);
        }
        return data;
    }

    //递归获取子节点留言
    private void getChildIds(LeaveWordsOutDto  parent,   List<LeaveWordsOutDto> list) {
        List<LeaveWordsOutDto> childs = new ArrayList<>();
        for (LeaveWordsOutDto leave : list) {
            //过滤父节点为空的数据
            if (leave.getParentId() == null) {
                continue;
            }
            // 判断是否存在子节点
            if (parent.getId().longValue() == leave.getParentId().longValue()) {
                childs.add(leave);
                // 递归遍历下一级
                getChildIds(leave, list);
            }
            parent.setChildren(childs);
        }
        return;
    }
}
